<template>
  <div class="production-plan">
    <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
    <h3 class="title">入库申请表</h3>
    
    <!-- 基本信息 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="单据主题">
            <el-input v-model="formData.documentSubject" placeholder="请输入主题" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据编号">
            <el-input v-model="formData.documentNumber" placeholder="请输入编号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="来源单据" prop="creator" >
            <el-input v-model="formData.sourceDocument" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <!-- 库管人员显示 -->
          <el-col :span="6">
              <el-form-item label="库管人员" >
              <el-input 
              placeholder="请输入" 
              v-model="formData.warehouseKeeper" 
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="申请人员">
            <el-input v-model="formData.applicant" placeholder="请输入备注" disabled />
          </el-form-item>
        </el-col>
         <el-col :span="6">
          <el-form-item label="申请时间">
            <el-input v-model="formData.applicationTime" placeholder="请输入"  disabled  />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入库类别">
            <el-input v-model="formData.stockInCategory" placeholder="请输入"   />
          </el-form-item>
        </el-col>
        <!-- 供应商显示 -->
        <el-col :span="6">
              <el-form-item label="供应商名称" >
                  <el-input 
                  placeholder="请输入" 
                  v-model="formData.supplierName" 
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openAssociatedItemDialog1">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
        </el-col>

        <el-col :span="6">
        <el-form-item label="备注">
            <el-input v-model="formData.remarks" placeholder="请填写" />
        </el-form-item>
        </el-col>
      </el-row>  
    </el-form>
    <!-- 物料明细明细 -->
    <div class="detail-section">
      <h4 class="sub-title">入库明细</h4>
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-table :data="planDetailsList" border style="width: 100%">
        <el-table-column label="产品名称" width="180px">
          <template #default="{ row }">
            <el-input 
              v-model="row.productName" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini"   @click="openProductNameDialog(row)">
                  <i class="el-icon-search"></i>
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <el-table-column label="产品编号">
          <template #default="{ row }">
            <el-input v-model="row.productNumber" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template #default="{ row }">
            <el-input v-model="row.specificationModel" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unit" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.unitPrice" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="申请入库数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.appliedStockInQuantity" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总金额">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.totalAmount" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="批号">
          <template #default="{ row }">
            <el-input v-model="row.batchNumber" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
         <el-table-column label="生产日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.productionDate"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="到货日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.arrivalDate"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
          <el-table-column label="有效日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.expiryDate"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="包装方式">
          <template #default="{ row }">
            <el-select 
              v-model="row.packagingMethod" 
              :disabled="row.isSaved"        
              placeholder="请选择包装方式"
              clearable>
              <el-option
                v-for="item in warehouseManagers"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remarks" type="textarea" rows="3" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
       <el-table-column fixed="right"  label="操作" width="180px">
          <template #default="{ row }">
            <!-- 移除单独保存明细按钮 -->
            <el-button size="small"  type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 文件上传 -->
     <div id="app">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>MinIO 文件上传</span>
        </div>
      </template>
      <el-form ref="formRef1" :model="formData1" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
    </el-card>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="key" label="文件名称" width="200" />
      <el-table-column prop="lastModified" label="创建时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.lastModified).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" min-width="200" />
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
            删除文件
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
      <p>确定要删除该文件吗？</p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
      <template #content>
        <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
      </template>
      <template #footer>
        <el-button @click="closeDownloadDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>



    <!--库管人员选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible"
      width="500px"
      title="库管人员选择"
      append-to-body
    >
      <el-table
        :data="associatedItems"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="userName" label="用户名称" />
        <el-table-column property="password" label="密码" />
        <el-table-column property="userNickName" label="昵称" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem">确定</el-button>
      </template>
    </el-dialog>

     <!-- 供应商选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible1"
      width="500px"
      title="供应商选择"
      append-to-body
    >
      <el-table
        :data="associatedItems1"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange1"
      >
       <el-table-column type="index" label="序号" />
        <el-table-column property="vendorName" label="供应商名称" />
        <el-table-column property="supplierNumber" label="供应商编号" />
        <el-table-column property="industry" label="供应商类别" />
        <el-table-column property="contact" label="联系人" />
        <el-table-column property="sex" label="性别" />
        <el-table-column property="origin" label="籍贯" />
        <el-table-column property="phone" label="手机号码" />
        <el-table-column property="email" label="邮箱" />
        <el-table-column property="addr" label="地址" />
        <el-table-column property="companyProfile" label="公司简介" />
        <el-table-column property="bank" label="开户银行" />
        <el-table-column property="accountName" label="账户名称" />
        <el-table-column property="bankCardNumber" label="银行卡号" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem1">确定</el-button>
      </template>
    </el-dialog>


     <!-- 入库申请明细产品名称选择对话框 -->
    <el-dialog
      v-model="productNameDialogVisible"
      width="500px"
      title="产品名称选择"
      append-to-body
    >
      <el-table
        :data="productNames"
        highlight-current-row
        border
        size="small"
        @current-change="handleProductNameChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickProductName">确定</el-button>
      </template>
    </el-dialog>


    
  </div>
</template>

<script setup>

import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { Materialwrite, Materialread } from '@/axios/axiosHelper';
import axios from 'axios';
// 移除未使用的 th
// import { th } from 'element-plus/es/locales.mjs';

const formRef = ref(null);
const currentUser = ref("admin");
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  id: '',
  documentSubject: "",
  documentNumber: "",
  sourceDocument: "",
  warehouseKeeper: "",
  applicant: currentUser.value,
  applicationTime: new Date().toISOString(),
  stockInCategory: "",
  supplierName: "",
  remarks: "",
});

// 主表单验证规则
const rules = reactive({
  documentSubject: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  documentNumber: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
});


// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 监听路由参数变化
watch(() => route.query, async (newQuery) => {
    if (newQuery.id) {
        await getProductionById(newQuery.id);
    } else {
        // 清空表单
        formData.documentSubject = "";
        formData.documentNumber = "";
        formData.sourceDocument = "";
        formData.warehouseKeeper = "";
        formData.applicant = currentUser.value;
        formData.applicationTime = new Date().toISOString();
        formData.stockInCategory = "";
        formData.supplierName = "";
        formData.remarks = "";
        formData.id = null;
        planDetailsList.value = [];
    }mainData
});

const getProductionById = async (id) => {
    try {
        const [mainResponse, detailResponse] = await Promise.all([
            axios.get('https://localhost:7090/api/Getm/FTStockInApplication', {
                params: { Id: id }
            }),
            axios.get('https://localhost:7090/api/Getm/FTStockInDetail', {
                params: { StockInDetailSId: id }
            })
        ]);

        if (mainResponse.data.code === 200) {
            const mainData = mainResponse.data.data[0];
            formData.documentSubject = mainData.documentSubject;
            formData.documentNumber = mainData.documentNumber;
            formData.sourceDocument = mainData.sourceDocument;
            formData.warehouseKeeper = mainData.warehouseKeeper;
            formData.applicant = mainData.applicant;
            formData.applicationTime = mainData.applicationTime;
            formData.stockInCategory = mainData.stockInCategory;
            formData.supplierName = mainData.supplierName;
            formData.remarks = mainData.remarks;
            formData.id = mainData.id;
        }
        if (detailResponse.data.code === 200) {
            planDetailsList.value = detailResponse.data.data.map(item => ({
              stockInDetailSId: item.stockInDetailSId || '',
                productName: item.productName || "",
                productNumber: item.productNumber || "",
                specificationModel: item.specificationModel || "",
                unit: item.unit || "",
                unitPrice: item.unitPrice || '',
                appliedStockInQuantity: item.appliedStockInQuantity || '',
                totalAmount: item.totalAmount || "",
                batchNumber: item.batchNumber || "",
                productionDate: item.productionDate || '',
                expiryDate: item.expiryDate || "",
                arrivalDate: item.arrivalDate || "",
                packagingMethod: item.packagingMethod || "",
                remarks: item.remarks || "",
                stockInApplicationId: item.stockInApplicationId || null,

              }));
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('数据加载失败，请检查网络或联系管理员');
    }
};


const saveAll = async () => {
  if (formRef.value) {
    const isValid = await formRef.value.validate();
    if (isValid) {
      try {
        // 保存主表单
        const response = await axios.put('https://localhost:7279/api/RKCK/UpdateStockInApplication', formData);
        if (response.data.code === 400) {
          formData.id = response.data.data.id;
          ElMessage.success('主表单保存成功');
          router.push('/GetStockInApplication');
          // 保存明细
          const saveDetailPromises = planDetailsList.value.map(async (row) => {
            const detailWithId = {
              ...row,
              stockInDetailSId: formData.id
            };
            const detailResponse = await axios.put(
              'https://localhost:7279/api/StockInDetailS/UpdateStockInDetail',
              detailWithId
            );
            if (detailResponse.data.code === 400) {
              row.isSaved = true;
              return true;
            } else {
              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
              return false;
            }
          });

          const results = await Promise.all(saveDetailPromises);
          if (results.every(result => result)) {
            ElMessage.success('所有明细保存成功');
            router.push('/GetStockInApplication');
          }
        } else {
          ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
      } catch (error) {
        // console.error('保存过程中发生错误:', error.response?.data);
        // ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      }
    }
  }
};
// 新增行
const addNewRow = () => {
    planDetailsList.value.push({
      stockInDetailSId:'',
    productName: "",
    productNumber: "",
    specificationModel: "",
    unit: "",
    unitPrice: 0,
    appliedStockInQuantity: 0,
    totalAmount: 0,
    batchNumber: "",
    productionDate: "",
    expiryDate: "",
    arrivalDate: "",
    packagingMethod: "",
    remarks: "",
    stockInApplicationId: 0,
    });
};

// 批量保存明细
const batchSaveDetails = async () => {
    if (!formData.bomid) {
        ElMessage.warning('请先保存主表单');
        return;
    }

    const detailsWithId = planDetailsList.value.map(detail => ({
        ...detail,
        id: formData.id
    }));

    try {
        const response = await Materialwrite.post(
            '/l-write/api/Ment/PLAddMaterials',
            detailsWithId
        );
        if (response.data.code === 400) {
            // 更新 planDetailsList 中的 productionScheduleDetailId
            planDetailsList.value = response.data.data.map((item, index) => ({
                ...planDetailsList.value[index],
                id: item.id
            }));
            ElMessage.success('明细批量保存成功');
        } else {
            ElMessage.error(`明细批量保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 修改单条明细
const UpdateDetail = async (row) => {
    // if (!formData.bomid) {
    //     ElMessage.warning('请先保存主表单');
    //     return;
    // }

    // const detailData = {
    //     ...row,
    //     bomid: formData.bomid
    // };

    // console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据

    try {
        const response = await Materialwrite.put(
            '/l-write/api/Ment/UpdateMaterialsChild',
            detailData
        );
        // console.log('后端返回的响应:', response); // 打印后端返回的响应

        if (response.data.code === 400) {
            ElMessage.success('明细更新成功');
        } else {
            ElMessage.error(`更新失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('更新错误:', error);
        ElMessage.error('更新失败，请检查网络或联系管理员');
    }
};

// 删除单条记录
const deleteDetail = async (bomid) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await Materialwrite.delete(
                `/l-write/api/Ment/DelMaterials`,
                {
                    params: { id: id.toString() }
                }
            );
            if (response.data.code === 300) {
                ElMessage.success('删除成功');
                ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错误:', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};



// ————————————————————————————————————产品名称查询————————————————————————————————————

// 产品名称数据
const productNames = ref([]);

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

// 获取产品信息
const fetchProducts = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      productNames.value = res.data.data;
      console.log("产品数据：", productNames.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    .catch(error => {
      // console.error('获取产品信息失败:', error);
      // ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    });
};



// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
  if (productNames.value.length === 0) {
    ElMessage.warning('产品信息正在加载，请稍后重试');
    return;
  }
  currentProductNameRow.value = row;
  productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
  currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
  if (currentProductName.value && currentProductNameRow.value) {
    currentProductNameRow.value.productName = currentProductName.value.productsName;
    currentProductNameRow.value.productNumber = currentProductName.value.productsNumber;
    currentProductNameRow.value.specificationModel = currentProductName.value.productsNum;
    currentProductNameRow.value.unit = currentProductName.value.productsUnit;
    currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
    productNameDialogVisible.value = false;
  }
};

onMounted(() => {
    if (route.query.id) {
        getProductionById(route.query.id);
    }   
  fetchProducts();
fetchAssociatedProjects();
  fetchProducts();
fetchAssociatedProjects1();
  //图片上传显示
    listObjects();
});

// ————————————————————————————————————库管人员查询————————————————————————————————————
// 对话框显示状态
const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});
// 库管人员数据
const associatedItems = ref([]);
// 打开库管人员选择对话框
const openAssociatedItemDialog = () => {
  associatedItemDialogVisible.value = true;
};
// 当前选中的库管人员行
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};

// 获取库管人员数据
const fetchAssociatedProjects = () => {
  axios.get('http://10.223.8.7:8000/read/api/User/GetUse')
    .then(res => {
      associatedItems.value = res.data.data;
    })
    .catch(error => {
      // console.error('获取关联项目数据失败:', error);
      // ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
    });
};



// 选择库管人员
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    formData.warehouseKeeper = currentAssociatedItem.value.userName;
    associatedItemDialogVisible.value = false;
  }
};




//
// ————————————————————————————————————供应商查询————————————————————————————————————


// 对话框显示状态
const associatedItemDialogVisible1 = ref(false);
const currentAssociatedItem1 = ref({});
// 库管人员数据
const associatedItems1 = ref([]);
// 打开库管人员选择对话框
const openAssociatedItemDialog1 = () => {
  associatedItemDialogVisible1.value = true;
};
// 当前选中的库管人员行
const handleAssociatedItemChange1 = (val) => {
  currentAssociatedItem1.value = val;
};

// 获取库管人员数据
const fetchAssociatedProjects1 = () => {
  axios.get('https://localhost:7095/api/Vendor/QueryVendor')
    .then(res => {
      associatedItems1.value = res.data.data;
    })
    .catch(error => {
      console.error('获取关联项目数据失败:', error);
      ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
    });
};



// 选择库管人员
const pickAssociatedItem1 = () => {
  if (currentAssociatedItem1.value) {
    formData.supplierName = currentAssociatedItem1.value.vendorName;
    associatedItemDialogVisible1.value = false;
  }
};




import { ElDialog } from 'element-plus';


const formRef1 = ref(null);
const uploadRef = ref(null);
const formData1 = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref('');
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

//文件
const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};
//图片上传显示
const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData1 = new FormData();
  formData1.append('file', options.file);
  const response = await axios.post(options.action, formData1, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};



</script>

<style scoped>
.production-plan {
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.sub-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.detail-section,
.attachment-section {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}
</style>